import { createRouter, createWebHistory } from "vue-router";
import { useAuthStore } from "@/store/modules/auth";
import { useMenuStore } from "@/store/modules/menu";
import { useConfigStore } from "@/store/modules/config";
import { systemRoutes, systemAuthRoutes } from "./modules/system";
import menuTool from "@/utils/menuRoute";
import NProgress from "nprogress";

//扁平化本地静态路由
export const staticRoutes = menuTool.getFlatStaticRoutesList(menuTool.staticRoutes());

// 引入 views 文件夹下所有 vue 文件，排除components文件夹
const modules = import.meta.glob(["@/views/**/*.vue", "!@/views/**/components"]);

// 创建路由
const router = createRouter({
  history: createWebHistory(),
  routes: [...systemRoutes, ...systemAuthRoutes],
  strict: false,
  scrollBehavior: () => ({ left: 0, top: 0 }),
});

//判断是否已加载过动态/静态路由
var isGetRouter = false;

/**
 * @description 路由拦截 beforeEach
 */
router.beforeEach((to, from, next) => {
  // 获取登录数据
  const authStore = useAuthStore();

  // 获取系统信息
  const configStore = useConfigStore();

  // 1.NProgress 开始
  NProgress.start();

  // 2.动态设置标题
  // document.title = to.meta.title ? `${to.meta.title} - ${import.meta.env.VITE_VUE_TITLE}` : `${import.meta.env.VITE_VUE_TITLE}`;
  document.title = to.meta.title ? `${to.meta.title} - ${configStore.siteTitle}` : `${configStore.siteTitle}`;

  // 3.判断是访访问的是静态auth路由，有 Token 就在当前页面，没有 Token 重置路由到登陆页
  /* systemAuthRoutes.forEach((item) => {
    if (item.path.toLocaleLowerCase() === to.path.toLocaleLowerCase()) {
      if (authStore.token) return next(from.fullPath);
      isGetRouter = false;
      return next();
    }
  }); */

  const authRoute = systemAuthRoutes.find((item) => item.path.toLowerCase() === to.path.toLowerCase());

  if (authRoute) {
    if (authStore.token) {
      NProgress.done();
      return next(from.fullPath);
    }
    isGetRouter = false;
    NProgress.done();
    return next();
  }

  // 4.判断是否有 Token，没有重定向到 login 页面
  if (!authStore.token) return next({ path: "/login", replace: true });

  // 5.添加静态/动态路由
  if (!isGetRouter) {
    // 添加静态路由
    staticRoutes.forEach((item) => {
      if (item.meta?.isFull) {
        router.addRoute(item);
      } else {
        router.addRoute("layout", item);
      }
    });

    //添加动态路由
    let apiMenu = menuTool.getFlatMenuList(useMenuStore().list);
    apiMenu.forEach((item) => {
      item.children && delete item.children;
      if (item.component && typeof item.component == "string") {
        item.component = modules["/src/views" + item.component + ".vue"];
      }
      if (item.meta.isFull) {
        router.addRoute(item);
      } else {
        router.addRoute("layout", item);
      }
    });
    isGetRouter = true;
    return next({ ...to, replace: true });
  }

  // 6.正常访问页面
  next();
});

export default router;
